package storage

import (
	"github.com/aliyun/aliyun-oss-go-sdk/oss"
	"github.com/gin-gonic/gin"
	"path/filepath"
)

var Oss = new(ossStorage)

type ossStorage struct{}

// 本地保存
func (s *ossStorage) Save(c *gin.Context, config *StructConfig) (*StructFile, error) {
	fd, headers, err := c.Request.FormFile("file")
	if err != nil {
		return nil, err
	}
	client, err := oss.New(config.Oss.Region, config.Oss.AccessKeyId, config.Oss.AccessKeySecret)
	if err != nil {
		return nil, err
	}
	// 填写存储空间名称
	bucket, err := client.Bucket(config.Oss.Bucket)
	if err != nil {
		return nil, err
	}
	// 将文件流上传
	err = bucket.PutObject(config.SavePath+config.SaveName, fd)
	if err != nil {
		return nil, err
	}
	// 文件后缀
	suffix := filepath.Ext(headers.Filename)
	file := StructFile{
		Storage:      "cos",
		OriginalName: headers.Filename,
		Name:         config.SaveName,
		Size:         headers.Size,
		Suffix:       suffix,
		Type:         headers.Header.Get("Content-Type"),
		Path:         config.SavePath + config.SaveName,
		Url:          "https://" + config.Oss.Bucket + "." + config.Oss.Region + "/" + config.SavePath + config.SaveName,
	}
	return &file, nil
}

// 删除文件
func (s *ossStorage) Del(config *StructConfig, objects []string) error {
	client, err := oss.New(config.Oss.Region, config.Oss.AccessKeyId, config.Oss.AccessKeySecret)
	if err != nil {
		return err
	}
	bucket, err := client.Bucket(config.Oss.Bucket)
	if err != nil {
		return err
	}
	// 填写需要删除的多个文件完整路径，文件完整路径中不能包含Bucket名称。
	//	// 将oss.DeleteObjectsQuiet设置为true，表示不返回删除结果。
	_, err = bucket.DeleteObjects(objects, oss.DeleteObjectsQuiet(true))
	if err != nil {
		return err
	}
	return nil
}
